package me.sapling;

import me.sapling.model.PageContent;
import me.sapling.view.AbstractPanel;
import me.sapling.view.FIFOPanel;
import me.sapling.view.LRUPanel;
import me.sapling.view.OPTPanel;

import javax.swing.*;
import java.awt.*;

/**
 * @author sapling
 */
public class ApplicationMain extends JFrame {

    private PageContent[] pages = {
			new PageContent(1),
			new PageContent(2),
			new PageContent(3),
			new PageContent(4),
			new PageContent(5),
			new PageContent(6),
			new PageContent(7),
			new PageContent(8),
			new PageContent(9)
	};
	private AbstractPanel panel;
	private JComboBox<String> arithmetic;
	private JButton start;
	private JTextField order;

	public ApplicationMain() {
		this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		this.setSize(800, 550);
		this.setLocationRelativeTo(this.getOwner());
		init();
	}

	private void init() {
		Container c = this.getContentPane();

		order = new JTextField("6,7,6,5,9,6,8,9,7,6,9,6", 24);

		this.arithmetic = new JComboBox<>(new String[]{
				"最佳置换算法(OPT)", "先进先出置换算法(FIFO)", "最近最久未用置换算法(LRU)"
		});
		JButton load = new JButton("加载");
		load.addActionListener(e -> {
			try {
				String orderStr = order.getText();
				String arrayStr[] = orderStr.split(",");
				PageContent[] contents = new PageContent[arrayStr.length];
				for (int i = 0; i < arrayStr.length; i++) {
					contents[i] = pages[Integer.parseInt(arrayStr[i]) - 1];
				}
				if (panel != null) {
					panel.destroy();
					c.remove(panel);
				}
				switch (arithmetic.getSelectedIndex()) {
					case 0:
						panel = new OPTPanel(pages, contents);
						break;
					case 1:
						panel = new FIFOPanel(pages, contents);
						break;
					case 2:
						panel = new LRUPanel(pages, contents);
						break;
					default:
						break;
				}
				c.add(panel);
				panel.start();
				validate();
				repaint();
				start.setEnabled(true);
			} catch (Exception e1) {
				JOptionPane.showMessageDialog(ApplicationMain.this, "请求序列输入错误：输入在1~9之间且以“,”间隔。");
			}
		});
		this.start = new JButton("开始");
		this.start.addActionListener(e -> {
			if (panel.isContentLoaded()) {
				panel.setStart();
				start.setEnabled(false);
			}
		});
		this.start.setEnabled(false);

		JPanel p = new JPanel();
		p.add(new JLabel("请求序列："));
		p.add(order);
		p.add(arithmetic);
		p.add(load);
		p.add(start);
		c.add(p, "South");
	}

	public static void main(String[] args) throws ClassNotFoundException,
			UnsupportedLookAndFeelException, InstantiationException, IllegalAccessException {
		UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		SwingUtilities.invokeLater(() -> new ApplicationMain().setVisible(true));
	}
}
